~ chicken-core (chicken-5) /manual/Getting started
Trap1[[tags: manual]]23== Getting started45CHICKEN is a compiler that translates Scheme source files into6C, which in turn can be fed to a C compiler to generate a7standalone executable. An interpreter is also available and can be8used as a scripting environment or for testing programs before9compilation.1011This chapter is designed to get you started with CHICKEN programming,12describing what it is and what it will do for you, and covering basic13use of the system. With almost everything discussed here, there is14more to the story, which the remainder of the manual reveals. Here, we15only cover enough to get you started. Nonetheless, someone who knows16Scheme already should be able to use this chapter as the basis for17writing and running small CHICKEN programs.1819=== Scheme2021Scheme is a member of the Lisp family of languages, of which Common22Lisp, Emacs Lisp and Clojure are other widely-known members. As with23Lisp dialects, Scheme features2425* a wide variety of programming paradigms, including imperative, functional, and object-oriented26* a very simple syntax, based upon nested parenthesization27* the ability to extend the language in meaningful and useful ways2829In contrast to Common Lisp, Scheme is very minimal, and tries to30include only those features absolutely necessary in programming. In31contrast to Emacs Lisp, Scheme is not anchored into a single program32(Emacs), and has a more modern and elegant language design. In contrast33to Clojure, Scheme provides only a very minimal set of concepts but allows34them to be used in very general ways with few restrictions.3536Scheme is defined in a document called ''The Revised^5 Report on the37Algorithmic Language Scheme'', or ''R5RS'' for short. (Yes, it really38has been revised five times, so an expanded version of its name would39be ''The Revised Revised Revised Revised Revised Report''.) A newer40report, ''R6RS'', was41released in 2007, but this report has attracted considerable42controversy, and a number of Scheme implementations have chosen43not to be compliant44with it. Yet another report was released in 2013 ("R7RS"), that was45less ambitious than R6RS and more minimal.4647CHICKEN fully complies with R5RS and, by using a separately available48extension also with the "R7RS small" language.4950Even though Scheme is consciously minimalist, it is recognized that a51language must be more than a minimal core in order to be52useful. Accordingly, the Scheme community uses a process known as53`Scheme Requests For Implementation' (SRFI, pronounced `SUR-fee') to54define new language features. A typical Scheme system therefore55complies with one of the Scheme reports plus some or all of the56accepted SRFIs.5758A good starting point for Scheme knowledge is59[[http://www.schemers.org]]. There you will find the defining reports,60FAQs, lists of useful books and other resources, and the SRFIs.6162=== CHICKEN6364CHICKEN Scheme combines an optimising compiler with a reasonably fast65interpreter. It supports almost all of R7RS and the important SRFIs.66The compiler generates portable C code that supports tail recursion,67first-class continuations and lightweight threads, and the interface to68and from C libraries is flexible, efficient, and easy to use. There are69hundreds of contributed CHICKEN libraries that make the programmer's70task easier. The interpreter allows interactive use, fast prototyping,71debugging, and scripting. The active and helpful CHICKEN community72fixes bugs and provides support. Extensive documentation is supplied.7374CHICKEN was developed by Felix L. Winkelmann over the period from 200075through 2007. In early 2008, Felix76asked the community to take over the responsibility of developing and77maintaining the system, though he still takes a strong interest in it,78and participates actively.7980CHICKEN includes8182* a Scheme interpreter that supports all of R5(7)RS Scheme, with83 only a few relatively minor omissions, and with many extensions84* a compatible compiler whose target is C, thus making porting to new85 machines and architectures relatively straightforward86* the C support allows Scheme code to include `embedded' C code,87 thus making it easy to invoke host OS or library88 functions89* a framework for language extensions, library modules that broaden90 the functionality of the system9192This package is distributed under the '''BSD license''' and as such is free93to use and modify as long as the original authors are acknowledged.9495Scheme cognoscenti will appreciate the method of compilation and the96design of the runtime-system, which follow closely Henry Baker's97[[https://web.archive.org/web/20200223051632/http://home.pipeline.com/~hbaker1/CheneyMTA.html|CONS Should Not98CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a99number of interesting properties.100101* Consing (creation of data on the heap) is inexpensive,102 because a generational garbage collection scheme is used in combination103 with allocating on the C stack, in which short-lived data structures are reclaimed104 extremely quickly.105106* Moreover, {{call-with-current-continuation}} involves only minimal107 overhead and CHICKEN does not suffer under any performance penalties if108 first-class continuations are used in complex ways.109110The generated C code fully supports tail-call optimization (TCO).111112Some of the features supported by CHICKEN:113114* Lightweight threads based on first-class continuations115* Record structures116* Extended comment- and string-literal syntaxes117* Libraries for regular expressions, string handling118* UNIX system calls and extended data structures119* Compiled C files can be easily distributed120* Allows the creation of fully self-contained statically linked executables121* On systems that support it, compiled code can be loaded dynamically122* Built-in support for cross-compilation123124CHICKEN has been used in many environments ranging from embedded125systems through desktop machines to large-scale server deployments.126The number of language extensions, or '''eggs''', is constantly growing:127128* extended language features129* development tools, such as documentation generators, debugging, and130 automated testing libraries131* interfaces to other languages such as Java, Python, and Objective-C132* interfaces to database systems, GUIs, and other libraries,133* network applications, such as servers and clients for ftp,134 smtp/pop3, irc, and http135* web servers and related tools, including URL parsing, HTML136 generation, AJAX, and HTTP session management137* data formats, including XML, JSON, and Unicode support138139This chapter provides you with an overview of the entire system, with140enough information to get started writing and running small Scheme141programs.142143=== CHICKEN repositories, websites and community144145The master CHICKEN website is146[[http://www.call-cc.org]]. Here you can find147basic information about CHICKEN, downloads and pointers to other key148resources.149150The CHICKEN wiki ([[http://wiki.call-cc.org]]) contains the most151current version of the User's manual, along with various tutorials and152other useful documents. The list of eggs is at153[[http://wiki.call-cc.org/egg-index|http://wiki.call-cc.org/egg-index]].154155A very useful search facility for questions about procedures and syntax156available for CHICKEN can be found at157[[http://api.call-cc.org]]. The CHICKEN issue tracker is at158[[http://bugs.call-cc.org]].159160The CHICKEN community has two major mailing lists. If you are a161CHICKEN user, {{chicken-users}}162([[http://lists.nongnu.org/mailman/listinfo/chicken-users]]) will be163of interest. The crew working on the CHICKEN system itself uses the164very low-volume {{chicken-hackers}} list165([[http://lists.nongnu.org/mailman/listinfo/chicken-hackers]]) for166communication. For other topic-specific mailing lists (e.g.,167announcements, security) and discussion groups, see168[[http://wiki.call-cc.org/discussion-groups|http://wiki.call-cc.org/discussion-groups]].169170There is also an IRC channel ({{#chicken}}) on171[[http://libera.chat|Libera.Chat]].172173=== Installing CHICKEN174175CHICKEN is available as C sources. Refer to the176{{README}} file in the distribution for instructions on installing it177on your system.178179Because it compiles to C, CHICKEN requires that a C compiler be180installed on your system. (If you're not writing embedded C code, you181can pretty much ignore the C compiler once you have installed it.)182183* On a Linux system, a C toolchain (e.g., GCC, clang) should be184 installed as part of the basic operating system, or should be185 available through the package management system (e.g., APT,186 Synaptic, RPM, or Yum, depending upon your Linux distribution).187* On Macintosh OS X, you will need the XCode tools, which are188 installable from the App Store.189* On Windows, you have three choices:190* Cygwin ([[https://www.cygwin.com/]]) provides a relatively191 full-featured Unix environment for Windows. CHICKEN works192 substantially the same in Cygwin and Unix.193* The GNU Compiler Collection has been ported to Windows, in the194 MinGW system ([[http://mingw-w64.org/]]). Unlike Cygwin,195 executables produced with MinGW do not need the Cygwin DLLs in order196 to run. MSYS is a companion package to MinGW; it provides a minimum197 Unix-style development/build environment, again ported from free198 software.199* You can build CHICKEN either with MinGW alone or with MinGW plus200 MSYS. Both approaches produce a CHICKEN built against the mingw headers201 and libraries.202 The only difference is the environment where you actually run make.203 {{Makefile.mingw}} can be used in {{cmd.exe}} with the version of make204 that comes with mingw. {{Makefile.mingw-msys}}205 uses unix commands such as {{cp}} and {{rm}}. The end product is the206 same.207208Refer to the {{README}} file for the version you're installing for209more information on the installation process.210211Alternatively, third party packages in binary format are212available. See213[[http://wiki.call-cc.org/platforms|http://wiki.call-cc.org/platforms]]214for information about how to obtain them.215216=== Development environments217218The simplest development environment is a text editor and terminal219window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for220using the interpreter and/or invoking the compiler. If you install one221of the line editing extensions (e.g., [[/egg/breadline|breadline]], [[/egg/linenoise|linenoise]]), you have some222useful command line editing features in the interpreter (e.g., Emacs223or vi-compatible line editing, customization).224225It will be helpful to use a text editor that knows Scheme; it can be painful226with editors that don't do parenthesis matching and automatic227indentation.228229In the rest of this chapter, we'll assume that you are using an editor230of your choice and a regular terminal window for executing your231CHICKEN code.232233=== The Read-Eval-Print loop234235To invoke the CHICKEN interpreter, you use the {{csi}} command.236237 $ csi238 CHICKEN239 (c) 2008-2021, The CHICKEN Team240 (c) 2000-2007, Felix L. Winkelmann241 Version 5.3.0 (rev e31bbee5)242 linux-unix-gnu-x86-64 [ 64bit dload ptables ]243244 Type ,? for help.245 #;1>246247This brings up a brief banner, and then the prompt. You can use this248pretty much like any other Scheme system, e.g.,249250 #;1> (define (twice f) (lambda (x) (f (f x))))251 #;2> ((twice (lambda (n) (* n 10))) 3)252 300253254Suppose we have already created a file {{fact.scm}} containing a255function definition.256257 (define (fact n)258 (if (= n 0)259 1260 (* n (fact (- n 1)))))261262We can now load this file and try out the function.263264 #;3> (load "fact.scm")265 ; loading fact.scm ...266 #;4> (fact 3)267 6268269The '''read-eval-print loop''' ('''REPL''') is the component of the270Scheme system that ''reads'' a Scheme expression, ''eval''uates it,271and ''prints'' out the result. The REPL's prompt can be customized272(see the [[Using the interpreter]])273but the default prompt, showing the number of the form, is quite274convenient.275276The REPL also supports debugging commands:277input lines beginning with a {{,}} (comma) are treated as special278commands. (See the [[Using the interpreter#Toplevel commands|full list]].)279280281==== Scripts282283You can use the interpreter to run a Scheme program from the command284line. For the following example we create a program that does a quick285search-and-replace on an input file; the arguments are a regular286expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:287288 xyzabcghi289 abxawxcgh290 foonly291292Next create the scheme code in a file called ''quickrep.scm'' with the293following little program:294295<enscript highlight=scheme>296;; irregex, the regular expression library, is one of the297;; libraries included with CHICKEN.298(import (chicken irregex)299 (chicken io))300301(define (process-line line re rplc)302 (irregex-replace/all re line rplc))303304(define (quickrep re rplc)305 (let ((line (read-line)))306 (if (not (eof-object? line))307 (begin308 (display (process-line line re rplc))309 (newline)310 (quickrep re rplc)))))311312;;; Does a lousy job of error checking!313(define (main args)314 (quickrep (irregex (car args)) (cadr args)))315</enscript>316317318To run it enter this in your shell:319320 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A321 xyzAghi322 Agh323 foonly324325The {{-ss}} option sets several options that work smoothly together to326execute a script. You can make the command directly executable from327the shell by inserting a [[Using the interpreter#Writing Scheme scripts|shebang line]]328at the beginning of the program.329330The {{-ss}} option arranges to call a procedure named {{main}}, with331the command line arguments, packed in a list, as its arguments. (There332are a number of ways this program could be made more idiomatic CHICKEN333Scheme, see the rest of the manual for details.)334335=== The compiler336337There are several reasons you might want to compile your code.338339* Compiled code executes substantially faster than interpreted340 code.341* You might want to deploy an application onto machines where the342 users aren't expected to have CHICKEN installed: compiled343 applications can be self-contained.344* Compiled code can access external libraries written in lower-level345 languages that follow the C calling convention.346347The CHICKEN compiler is provided as the command {{chicken}}, but in348almost all cases, you will want to use the {{csc}} command349instead. {{csc}} is a convenient driver that automates compiling350Scheme programs into C, compiling C code into object code, and linking351the results into an executable file. (Note: in a Windows environment352with Visual Studio, you may find that {{csc}} refers to Microsoft's353C# compiler. There are a number of ways of sorting this out, of which354the simplest is to rename one of the two tools, and/or to355organize your {{PATH}} according to the task at hand.)356357We can compile our factorial function, producing a file named358{{fact.so}} (''shared object'' in Linux-ese, the same file extension is359used in Windows, rather than {{dll}})360361 chicken$ csc -shared fact.scm362 chicken$ csi -quiet363 #;1> (load "fact.so")364 ; loading fact.so ...365 #;2> (fact 6)366 720367368On any system, we can just compile a program directly into an369executable. Here's a program that tells you whether its argument is a370palindrome.371372<enscript highlight=scheme>373(import (chicken process-context)) ; for "command-line-arguments"374375(define (palindrome? x)376 (define (check left right)377 (if (>= left right)378 #t379 (and (char=? (string-ref x left) (string-ref x right))380 (check (add1 left) (sub1 right)))))381 (check 0 (sub1 (string-length x))))382383(let ((arg (car (command-line-arguments))))384 (display385 (string-append arg386 (if (palindrome? arg)387 " is a palindrome\n"388 " isn't a palindrome\n"))))389</enscript>390391We can compile this program using {{csc}}, creating an executable392named {{palindrome}}.393394 $ csc -o palindrome palindrome.scm395 $ ./palindrome level396 level is a palindrome397 $ ./palindrome liver398 liver isn't a palindrome399400CHICKEN supports separate compilation, using some extensions to401Scheme. Let's divide our palindrome program into a library module402({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).403404Here's the external library. We {{declare}} that {{pal-proc}} is a405''unit'', which is the basis of separately-compiled modules in406CHICKEN. (Units deal with separate compilation, but don't necessarily407involve separated namespaces; namespaces can be implemented by408[[/manual/Modules|modules]].)409410<enscript highlight=scheme>411;;; Library pal-proc.scm412(declare (unit pal-proc))413414(define (palindrome? x)415 (define (check left right)416 (if (>= left right)417 #t418 (and (char=? (string-ref x left) (string-ref x right))419 (check (add1 left) (sub1 right)))))420 (check 0 (sub1 (string-length x))))421</enscript>422423Next we have some client code that ''uses'' this separately-compiled424module.425426<enscript highlight=scheme>427;;; Client pal-user.scm428(declare (uses pal-proc))429430(import (chicken process-context))431432(let ((arg (car (command-line-arguments))))433 (display434 (string-append arg435 (if (palindrome? arg)436 " is a palindrome\n"437 " isn't a palindrome\n"))))438</enscript>439440Now we can compile and link everything together. (We show the compile441and link operations separately, but they can of course be combined442into one command.)443444 $ csc -c pal-proc.scm445 $ csc -c pal-user.scm446 $ csc -o pal-separate pal-proc.o pal-user.o447 $ ./pal-separate level448 level is a palindrome449450The "unit" mechanism is relatively low-level and requires some451familiarity with underlying mechanism used to manage compilation452units. See [[Units and linking model]] for more information.453454=== Installing an egg455456Installing eggs is quite straightforward on systems that support457dynamic loading (that would include *BSD, Linux, Mac OS X,458Solaris, and Windows). The command {{chicken-install}} will fetch an459egg from the master CHICKEN repository, and install it on your local460system.461462In this example, we install the {{uri-common}} egg, for parsing463Uniform Resource Identifiers.464465 $ chicken-install uri-common466467{{chicken-install}} connects to a mirror of the egg repository and468retrieves the egg contents. If the egg has any uninstalled469dependencies, it recursively installs them. Then it builds the egg470code and installs the resulting extension into the471local CHICKEN repository.472473Now we can use our new egg.474475 #;1> (import uri-common)476 ; loading /usr/lib/chicken/9/uri-common.import.so ...477 ; [... other loaded files omitted for clarity ...]478479 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))480 "www.foobar.org"481482=== Accessing C libraries483484Because CHICKEN compiles to C, and because a foreign function485interface is built into the compiler, interfacing to a C library is486quite straightforward. This means that any facility available487on the host system is accessible from CHICKEN, with more or less488work.489490Let's create a simple C library, to demonstrate how this491works. Here we have a function that will compute and return the '''n'''th492Fibonacci number. (This isn't a particularly good use of C here,493because we could write this function just as easily in Scheme, but a494real example would take far too much space here.)495496 /* fib.c */497 int fib(int n) {498 int prev = 0, curr = 1;499 int next;500 int i;501 for (i = 0; i < n; i++) {502 next = prev + curr;503 prev = curr;504 curr = next;505 }506 return curr;507 }508509Now we can call this function from CHICKEN.510511 ;;; fib-user.scm512 (import (chicken foreign) (chicken format))513514 #>515 extern int fib(int n);516 <#517 (define xfib (foreign-lambda int "fib" int))518 (do ((i 0 (+ i 1))) ((> i 10))519 (printf "~A " (xfib i)))520 (newline)521522The syntax {{#>...<#}} allows you to include literal C (typically523external declarations) in your CHICKEN code. We access {{fib}} by524defining a {{foreign-lambda}} for it, in this case saying that the525function takes one integer argument (the {{int}} after the function526name), and that it returns an integer result (the {{int}} before.) Now we can invoke527{{xfib}} as though it were an ordinary Scheme function.528529 $ gcc -c fib.c530 $ csc -o fib-user fib.o fib-user.scm531532If using MinGW on Windows,533534 > gcc -c fib.c -o fib.obj535 > csc -o fib-user fib.obj fib-user.scm536537Then run the executable.538 $ ./fib-user539 0 1 1 2 3 5 8 13 21 34 55540541Those who are interfacing to substantial C libraries should consider542using the [[/egg/bind|bind egg]].543544---545546Back to [[The User's Manual]]547548Next: [[Using the interpreter]]